"""
FlowScape 后端主应用
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import logging
from datetime import datetime

from config import settings
from app.api import api_router
from app.core.response import create_response
from app.api.routes.upload import get_files_list
from fastapi import Depends
from sqlalchemy.orm import Session
from app.core.database import get_db

# 配置日志
logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL),
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)

# 创建FastAPI应用
app = FastAPI(
    title=settings.PROJECT_NAME,
    description=settings.PROJECT_DESCRIPTION,
    version=settings.API_VERSION,
    debug=settings.DEBUG,
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加/api/files/list端点，直接指向upload模块中的get_files_list函数
@app.get("/api/files/list", tags=["Upload"])
async def api_files_list(db: Session = Depends(get_db)):
    """
    根级别文件列表端点，兼容/api/files/list请求
    直接调用upload模块中的get_files_list函数
    """
    return await get_files_list(db)

# 注册API路由
app.include_router(api_router, prefix=settings.API_PREFIX)


@app.get("/", tags=["Root"])
async def root():
    """根路径 - 健康检查"""
    return create_response(
        data={
            "name": settings.PROJECT_NAME,
            "version": settings.API_VERSION,
            "status": "running",
            "timestamp": datetime.now().isoformat(),
        },
        message="FlowScape Backend is running",
    )


@app.get("/health", tags=["Health"])
async def health_check():
    """健康检查接口"""
    return create_response(
        data={
            "status": "healthy",
            "uptime": "运行正常",
            "timestamp": datetime.now().isoformat(),
        }
    )


# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    """全局异常处理器"""
    logger.error(f"Unhandled exception: {exc}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "status": "error",
            "error": {
                "code": "INTERNAL_ERROR",
                "message": "服务器内部错误",
                "details": str(exc) if settings.DEBUG else None,
            },
            "timestamp": datetime.now().isoformat(),
        },
    )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "app.main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
    )
